﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Windows.Forms;

namespace LibraryManagement.Inventory
{
    public partial class InvBookIssue : Form
    {
        private decimal? id;
        private decimal libCode;
        private LibManagementEntities context;
        private MemberDetail OMemberDetails;
        private BookDetail OBookDetails;
        private List<BookDetail> listBooks;
        private frmSelectMembers frmSelectMembers;
        private decimal bookLimit;
        private int issuedBooks;
        private BookTransaction OBookTransactions;
        private decimal? dueDate;
        private List<decimal> listLibCodes;

        public InvBookIssue()
        {
            InitializeComponent();
        }

        public InvBookIssue(decimal? id, frmSelectMembers frmSelectMembers)
        {
            InitializeComponent();
            this.id = id;
            context = new LibManagementEntities();
            listBooks = new List<BookDetail>();
            listLibCodes = new List<Decimal>();
            this.frmSelectMembers = frmSelectMembers;
        }

        private void InvBookIssue_Load(object sender, EventArgs e)
        {
            OMemberDetails = context.MemberDetails.Single(x => x.Id == (decimal)id);
            bookLimit = context.Categories.Single(x => x.CategoryId == OMemberDetails.CategoryId).BookLimit;
            dueDate = context.Categories.Single(x => x.CategoryId == OMemberDetails.CategoryId).DueDate;
            txtMemberName.Text = OMemberDetails.Name;
            txtBranch.Text = OMemberDetails.Branch1.BranchShortName;
            txtYear.Text = OMemberDetails.Year1.YearInWords;
            txtEnrollmentNo.Text = OMemberDetails.MemberEnrollmentNo;
            txtYear.Text = OMemberDetails.Year.ToString();
            issuedBooks = context.BookTransactions.Where(x => x.MemberId == id && x.Issued == true).ToList().Count;
            txtBooksIssued.Text = (issuedBooks).ToString();
            txtDues.Text = context.BookTransactions.Where(x => x.MemberId == id).Select(x => x.Dues).Sum().ToString();
            SetAvailableSlots();
            clsMethods.LoadImageFromBytes(OMemberDetails.Image, OMemberDetails, pcbMember);
        }

        private void SetAvailableSlots()
        {
            var availableSlots = (bookLimit - issuedBooks) - (lsbIssuedBooks.Items.Count);
            lnlAvailableSlots.Text = "Available Slots: " + availableSlots;
            if (availableSlots <= 0)
                btnAdd.Enabled = false;
            else
                btnAdd.Enabled = true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            frmSelectMembers.Enabled = true;
            this.Close();
        }

        private void libTextBox1_TextChanged(object sender, EventArgs e)
        {
            if (txtBookCode.Text.Trim() != "" && txtBookCode.Text != null)
            {
                if (Decimal.TryParse(txtBookCode.Text, out libCode))
                {
                    try
                    {
                        OBookDetails = context.BookCopies.Single(x => x.LibCode == libCode).BookDetail;
                        txtAuthor1.Text = OBookDetails.Author1;
                        txtAuthor2.Text = OBookDetails.Author2;
                        txtAuthor3.Text = OBookDetails.Author3;
                        txtPublisher.Text = OBookDetails.Publisher;
                        txtTitle.Text = OBookDetails.Title;
                        txtYearOfEdition.Text = OBookDetails.YearOfEdition.ToString();
                        txtISBN.Text = OBookDetails.ISBN.ToString();
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message == "Sequence contains no elements")
                        { }
                        else
                        {

                        }
                    }
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtBookCode.Text != null || txtBookCode.Text.Trim() != "")
                {
                    BookDetail book = context.BookCopies.Single(x => x.LibCode == libCode).BookDetail;
                    if (!listBooks.Contains(book))
                    {
                        listLibCodes.Add(libCode);
                        listBooks.Add(book);
                        SetListBox();
                        SetAvailableSlots();
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        private void SetListBox()
        {
            lsbIssuedBooks.DataSource = null;
            lsbIssuedBooks.SetDataSource(listBooks, "Title", "Id");
            lsbIssuedBooks.Refresh();
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (lsbIssuedBooks.SelectedIndex != -1)
            {
                listLibCodes.Remove(libCode);
                listBooks.Remove(context.BookDetails.Single(x => x.Id == (decimal)lsbIssuedBooks.SelectedValue));
                SetListBox();
                SetAvailableSlots();
            }
        }

        private void InvBookIssue_FormClosed(object sender, FormClosedEventArgs e)
        {
            frmSelectMembers.Enabled = true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                context = new LibManagementEntities();
                OBookTransactions = new BookTransaction();
                using (TransactionScope scope = new TransactionScope())
                {
                    var i = 0; // Using this variable to enumerate through the libcodes.
                    foreach (BookDetail book in lsbIssuedBooks.Items)
                    {
                        OBookTransactions.BookId = book.Id;
                        OBookTransactions.BookLibCode = listLibCodes[i];
                        OBookTransactions.DateOfIssue = DateTime.Today;
                        OBookTransactions.DateOfSubmission = DateTime.Today.AddDays((double)dueDate);
                        OBookTransactions.Issued = true;
                        OBookTransactions.MemberEnrollmentNo = OMemberDetails.MemberEnrollmentNo;
                        OBookTransactions.MemberId = OMemberDetails.Id;
                        OBookTransactions.SessionId = clsStatics.currentActiveSessionId;
                        context.BookTransactions.Add(OBookTransactions);
                        context.SaveChanges();
                        i++;
                    }
                    scope.Complete();
                }
                this.Close();
            }
            catch (Exception ex)
            {
                if (ex.Message == "An error occurred while updating the entries. See the inner exception for details.")
                {
                    if ((ex.InnerException).Message == "An error occurred while updating the entries. See the inner exception for details.")
                    {
                        var msg = ((ex.InnerException).InnerException).Message;
                        var listMsg = msg.Split(new char[] { '.' }).ToList();
                        if (listMsg[0] == "Violation of UNIQUE KEY constraint 'IX_BookTransactions'")
                            MessageBox.Show("Book already issued.");
                    }
                }
            }
        }
    }
}
